<template>
	<view class="container">
		<!-- 顶部导航栏 - 固定定位 -->
		<view class="fixed-nav">
			<customNavTabVue></customNavTabVue>
		</view>

		<!-- 顶部占位，防止内容被导航栏遮挡 -->
		<view class="nav-placeholder" :style="{ height: navHeight + 'px' }"></view>

		<!-- 主内容区域 -->
		<view class="content-area">
			<!-- 下拉刷新提示 -->
			<view class="refresh-indicator" v-if="isRefreshing">
				<uni-icons type="spinner-cycle" size="24" color="#999"></uni-icons>
				<text>正在刷新...</text>
			</view>

			<!-- 骨架屏 -->
			<view class="skeleton-container" v-if="loading && !flowList.length">
				<skeleton :show-cards="true" :cards-count="4" card-width="48%" card-height="460rpx" card-margin="20rpx">
				</skeleton>
			</view>

			<!-- 笔记内容 -->
			<scroll-view class="content-list" scroll-y refresher-enabled @refresherrefresh="onRefresh"
				:refresher-triggered="isRefreshing" show-scrollbar="false" scroll-with-animation
				@scrolltolower="loadMore">
				<!-- 有数据时显示瀑布流 -->
				<view class="waterfall" v-if="flowList && flowList.length > 0">
					<view class="waterfall-item" v-for="(item, index) in flowList" :key="index"
						@click="goToDetail(item)">
						<image class="item-image" :src="item.image" mode="widthFix"></image>
						<view class="item-info">
							<text
								class="item-title">{{item.content.length > 10 ? item.content.substring(0, 10) + '...' : item.content}}</text>
							<view class="item-user">
								<view class="user-info">
									<image class="user-avatar" :src="item.avatar" mode="aspectFill"></image>
									<text class="user-name">{{item.userName}}</text>
								</view>
								<view class="donate-btn" v-if="isDetele == 0" @click.stop="handleReward(item)">
									<text>施舍</text>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 无数据时显示空状态 -->
				<view class="empty-state" v-else-if="!loading && !flowList.length">
					<view class="empty-icon">
						<uni-icons type="folder-add" size="50" color="#cccccc"></uni-icons>
					</view>
					<text class="empty-text">暂无帖子</text>
					<text class="empty-tips">快去发布你的第一篇帖子吧</text>
				</view>

				<!-- 加载更多状态 -->
				<view class="loading-more" v-if="loadStatus.status === 'loading' && flowList.length > 0">
					<uni-icons type="spinner-cycle" size="20" color="#999"></uni-icons>
					<text>加载中...</text>
				</view>
				<view class="no-more" v-if="this.page==this.pages">
					<text>没有更多了</text>
				</view>
			</scroll-view>
		</view>

		<!-- 回到顶部按钮 -->
		<view class="back-to-top" v-if="scrollTop > 300" @click="scrollToTop">
			<uni-icons type="top" size="20" color="#ffffff"></uni-icons>
		</view>
		<!-- 打赏礼物弹窗 -->
		<uni-popup ref="giftPopup" type="bottom">
			<view class="gift-popup">
				<view class="gift-header">
					<text class="gift-title">赠送礼物</text>
					<view class="close-btn" @click="closeGiftPopup">
						<uni-icons type="closeempty" size="24" color="#666"></uni-icons>
					</view>
				</view>
				<view class="gift-grid">
					<view class="gift-item" :class="{ active: selectedGift && selectedGift.id === gift.id }"
						v-for="(gift, index) in giftList" :key="index" @click="selectGift(gift)">
						<image class="gift-icon" :src="gift.icon" mode="aspectFit"></image>
						<text class="gift-name">{{gift.name}}</text>
						<text class="gift-price">￥{{gift.price}}</text>
					</view>
				</view>
				<view class="gift-footer">
					<button class="send-btn" @click="sendGift">赠送</button>
				</view>
			</view>
		</uni-popup>
		<!-- 底部导航栏 -->
		<tabBarVue></tabBarVue>
	</view>
</template>

<script>
	import customNavTabVue from '../../compents/custom-nav-tab/custom-nav-tab.vue'
	import tabBarVue from '../../compents/tab-bar/tab-bar.vue';
	import Skeleton from '../../compents/skeleton/skeleton.vue';
	import {
		getpostsList,
		getGifts,
		payOrders,
		getSetings
	} from '../../request/API';

	export default {
		data() {
			return {
				flowList: [], // 瀑布流数据
				page: 1,
				pages: 10, // 总页数
				navHeight: 0,
				scrollTop: 0,
				loading: true, // 数据加载状态
				clickData: 0, // 点击的帖子id
				selectedGift: null,
				isRefreshing: false,
				// 加载状态控制
				loadStatus: {
					status: 'loadmore', // loadmore-加载前的状态，loading-加载中的状态，nomore-没有更多的状态
					addTime: 0, // 触发瀑布流加载更多的时间戳
				},
				giftList: [],
				isDetele: 0
			}
		},
		components: {
			tabBarVue,
			customNavTabVue,
			Skeleton
		},
		// 页面加载时
		onLoad() {
			this.getNavHeight();
			this.init();
		},

		// 页面显示时
		onShow() {
			// 页面显示时，可以执行一些初始化逻辑
		},
		// 页面滚动时
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		// 页面触底时
		onReachBottom() {
			// 如果当前状态是可以加载更多，则加载更多数据
			if (this.loadStatus.status === 'loadmore') {
				this.loadMore();
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.onRefresh();
		},
		methods: {
			selectGift(gift) {
				this.selectedGift = gift
			},
			// 获取导航栏高度
			getNavHeight() {
				const systemInfo = uni.getSystemInfoSync();
				this.navHeight = 44 + systemInfo.statusBarHeight;
			},
			// 初始化数据
			async init() {
				this.loading = true;
				let code = await getSetings();
				this.isDetele = code.data.isDelete;
				this.isRefreshing = true;
				this.page = 1;
				try {
					const {
						data
					} = await getpostsList(this.page);
					console.log(data);
					let res = await getGifts();
					this.giftList = res.data;
					// 处理API返回的数据结构
					if (data.list) {
						this.flowList = data.list;
						this.page = data.pageNum || 1;
						this.pages = data.pages || 1;
						// 设置加载状态
						this.loadStatus.status = this.page < this.pages ? 'loadmore' : 'nomore';
					} else {
						// 如果返回的不是分页结构，就按照列表处理
						this.flowList = Array.isArray(data) ? data : [];
						this.loadStatus.status = this.flowList.length >= 10 ? 'loadmore' : 'nomore';
					}
				} catch (e) {
					console.error('初始化失败:', e);
					this.loadStatus.status = 'nomore';
				} finally {
					this.loading = false;
					this.isRefreshing = false;
					// 确保停止下拉刷新
					uni.stopPullDownRefresh();
				}
			},
			// 加载更多数据
			async loadMore() {
				// 如果没有更多数据或已经到最后一页，不再加载
				if (this.loadStatus.status === 'nomore' || this.page >= this.pages) {
					this.loadStatus.status = 'nomore';
					return;
				}

				// 更新加载状态为loading
				this.loadStatus.status = 'loading';

				try {
					const {
						data
					} = await getpostsList(this.page + 1);

					// 更新页码
					this.page = data.pageNum || (this.page + 1);

					if (data.list && data.list.length > 0) {
						// 更新数据列表
						this.flowList = [...this.flowList, ...data.list];

						// 更新加载状态
						this.loadStatus.status = this.page < (data.pages || 1) ? 'loadmore' : 'nomore';
					} else {
						this.loadStatus.status = 'nomore';
					}
				} catch (e) {
					console.error('加载更多失败:', e);
					this.loadStatus.status = 'loadmore'; // 加载失败时，允许重试
				}
			},
			// 下拉刷新
			async onRefresh() {
				if (this.isRefreshing) return;
				await this.init();
			},
			// 跳转到详情页
			goToDetail(item) {
				console.log('跳转到详情页', item);
				getApp().globalData.data = item;
				uni.navigateTo({
					url: "/pages/tong/tong"
				});
			},
			// 回到顶部
			scrollToTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},
			handleReward(item) {
				this.clickData = item.id;
				this.$refs.giftPopup.open()
			},
			closeGiftPopup() {
				this.clickData = 0;
				this.$refs.giftPopup.close()
			},
			sendGift() {
				let that = this;
				if (!this.selectedGift) {
					uni.showToast({
						title: '请选择礼物',
						icon: 'none'
					})
					return
				}
				uni.showModal({
					title: '确认支付',
					content: `确定要支付${this.selectedGift.price}元赠送${this.selectedGift.name}吗？`,
					success: async (res) => {
						if (res.confirm) {
							uni.getProvider({
								service: "payment",
								async success(payMent) {
									let {
										data
									} = await payOrders({
										goodId: that.selectedGift.id,
										userId: uni.getStorageSync("userId"),
										postId: that.clickData
									});
									uni.requestPayment({
										orderInfo: that.selectGift.name,
										provider: payMent.provider[0],
										nonceStr: data.nonceStr,
										package: data.packageStr,
										signType: data.signType,
										paySign: data.paySign,
										timeStamp: data.timeStamp
									})
								}
							})

							uni.showToast({
								title: '赠送成功',
								icon: 'success'
							})
							this.closeGiftPopup()
						}
					}
				})
			},
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		position: relative;
	}

	/* 固定导航栏样式 */
	.fixed-nav {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		background-color: #ffffff;
		box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
	}

	/* 导航栏占位 */
	.nav-placeholder {
		width: 100%;
	}

	/* 刷新指示器 */
	.refresh-indicator {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 50rpx;
		width: 100%;
		padding: 10rpx 0;
		gap: 8rpx;
	}

	.content-area {
		padding-bottom: 80rpx;
	}

	.content-list {
		height: calc(100vh - 88px - 80rpx);
		box-sizing: border-box;
		margin-bottom: 100rpx;
	}

	.waterfall {
		padding: 8rpx;
		column-count: 2;
		column-gap: 8rpx;
	}

	.waterfall-item {
		break-inside: avoid;
		margin-bottom: 12rpx;
		border-radius: 12rpx;
		overflow: hidden;
		background: #fff;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		transition: all 0.2s;
	}

	.waterfall-item:active {
		transform: scale(0.98);
	}

	.item-image {
		width: 100%;
		height: auto;
		display: block;
		background-color: #f5f5f5;
		vertical-align: bottom;
		/* 消除图片底部间隙 */
	}

	.item-info {
		padding: 12rpx 12rpx 10rpx;
		display: flex;
		flex-direction: column;
	}

	.item-title {
		font-size: 28rpx;
		color: #333;
		line-height: 1.3;
		margin-bottom: 10rpx;
		display: block;
		overflow: hidden;
		/* 添加两行省略 */
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		word-break: break-all;
	}

	.item-price {
		font-size: 32rpx;
		color: #ff2442;
		font-weight: bold;
		display: block;
		margin-bottom: 12rpx;
	}

	.item-user {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 12rpx;
		padding-top: 8rpx;
	}

	.user-info {
		display: flex;
		align-items: center;
		overflow: hidden;
		max-width: 65%;
		/* 限制用户信息区域宽度，避免挤压按钮 */
	}

	.user-avatar {
		width: 36rpx;
		height: 36rpx;
		border-radius: 50%;
		margin-right: 6rpx;
		flex-shrink: 0;
	}

	.user-name {
		font-size: 24rpx;
		color: #666;
		max-width: 120rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.interaction-info {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.like-info,
	.comment-info {
		display: flex;
		align-items: center;
		gap: 4rpx;
	}

	.like-info text,
	.comment-info text {
		font-size: 24rpx;
		color: #999;
	}

	/* 空状态样式 */
	.empty-state {
		padding: 120rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.empty-icon {
		margin-bottom: 30rpx;
	}

	.empty-text {
		font-size: 32rpx;
		color: #666;
		margin-bottom: 16rpx;
	}

	.empty-tips {
		font-size: 26rpx;
		color: #999;
	}

	/* 压缩加载更多区域 */
	.loading-more,
	.no-more {
		text-align: center;
		padding: 10rpx 0;
		color: #999;
		font-size: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 5rpx;
	}

	/* 回到顶部按钮 */
	.back-to-top {
		position: fixed;
		right: 30rpx;
		bottom: 160rpx;
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: rgba(0, 0, 0, 0.5);
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 99;
		transition: all 0.3s;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
	}

	.back-to-top:active {
		transform: scale(0.9);
	}

	/* 施舍按钮样式 */
	.donate-btn {
		min-width: 80rpx;
		height: 42rpx;
		background-color: #ff4f4f;
		color: #fff;
		font-size: 22rpx;
		font-weight: 500;
		border-radius: 21rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 12rpx;
		box-shadow: 0 2rpx 6rpx rgba(255, 79, 79, 0.2);
		transition: all 0.2s;
	}

	.donate-btn:active {
		transform: scale(0.95);
		opacity: 0.9;
	}

	.gift-popup {
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding-bottom: constant(safe-area-inset-bottom);
		/* 兼容 iOS < 11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		position: relative;
		z-index: 999;
	}

	.uni-popup .uni-popup__wrapper {
		padding-bottom: 0 !important;
	}

	.uni-popup-bottom {
		bottom: 0;
	}

	.gift-header {
		padding: 24rpx 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.gift-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.close-btn {
		padding: 10rpx;
	}

	.gift-grid {
		max-height: 400rpx;
		/* 限制最大高度，约两行礼物的高度 */
		overflow-y: auto;
		padding: 20rpx 20rpx 0;
		display: flex;
		flex-wrap: wrap;
		align-content: flex-start;
	}

	.gift-item {
		width: 25%;
		padding: 16rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}

	.gift-item.active {
		background: rgba(255, 36, 66, 0.05);
		border-radius: 12rpx;
	}

	.gift-icon {
		width: 88rpx;
		height: 88rpx;
		margin-bottom: 8rpx;
	}

	.gift-name {
		font-size: 24rpx;
		color: #333;
		margin-bottom: 4rpx;
	}

	.gift-price {
		font-size: 24rpx;
		color: #ff2442;
	}

	.gift-footer {
		padding: 20rpx 30rpx;
		border-top: 1rpx solid #f5f5f5;
	}

	.gift-footer .send-btn {
		height: 88rpx;
		line-height: 88rpx;
		background: linear-gradient(to right, #ff2442, #ff6b6b);
		color: #fff;
		font-size: 32rpx;
		font-weight: 500;
		border-radius: 44rpx;
		text-align: center;
	}

	.gift-footer .send-btn:active {
		opacity: 0.9;
	}

	.skeleton-container {
		padding: 20rpx;
	}

	.skeleton-container .skeleton-cards {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		margin: 0 -10rpx;
	}

	.skeleton-container .skeleton-card {
		margin-bottom: 20rpx !important;
		border-radius: 12rpx;
	}
</style>